package client;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchService;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Configuration
{	
	static public final String STORAGE_PATH = "./storage";
	static public long TRAVERSE_PERIOD = 10000;
	static public long SYNCHRONIZE_PERIOD = 1000;
	static public long SHARE_CHECK_PERIOD = 1000;
	static public long RETRY_PERIOD = 30000;
    static private final String configureFilePath = "config.xml";
    static private String homeDir = "mySynDir";
    static private WatchService folderWatcher;

    static public WatchService getFolderWatcher()
    {
	if (folderWatcher == null)
	{
	    try
	    {
		folderWatcher = FileSystems.getDefault().newWatchService();
	    } 
	    catch (IOException e)
	    {
		// TODO Auto-generated catch block
		System.err.println("Failed to create folder watcher service!");
	    }
	}
	return folderWatcher;
    }
    
    
    
    static public void readConfigurationFile()
    {
	File configureFile = new File(configureFilePath);
	if (!configureFile.canRead())
	{
	    System.err.println("Failed to configuration file, default setting will be used");
	    return;
	}
	try
	{
	    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
	    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
	    Document doc = dBuilder.parse(configureFile);
	    doc.getDocumentElement().normalize();
	    NodeList nodeList;
	    Element node;
	    
	    nodeList = doc.getElementsByTagName("HomeDir");
	    node = (Element )nodeList.item(0);
	    
	   String thomeDir = node.getAttribute("value");
	    if (thomeDir==null){return;}
	    homeDir = thomeDir;
	    
	} catch (Exception e)
	{
	    e.printStackTrace();
	}
    }

    public static String getConfigurefilepath()
    {
	return configureFilePath;
    }

    /**
     * 
     * @return absolute path of homeDirectory
     */
    public static Path getHomePath()
    { 
//    	/System.out.println(homeDir);
    	Path p = Paths.get(homeDir);
    	try
    	{
    	p = p.toAbsolutePath();
    	}
    	catch (Exception e)
    	{e.printStackTrace();}
    	return p;
    }

}
